package com.huika.renrench.ui;

import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.CancelableCallback;
import com.amap.api.maps.AMap.InfoWindowAdapter;
import com.amap.api.maps.AMap.OnInfoWindowClickListener;
import com.amap.api.maps.AMap.OnMarkerClickListener;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.navi.AMapNavi;
import com.amap.api.navi.AMapNaviListener;
import com.amap.api.navi.RoutePlanErrCode;
import com.amap.api.navi.model.AMapNaviInfo;
import com.amap.api.navi.model.AMapNaviLocation;
import com.amap.api.navi.model.AMapNaviPath;
import com.amap.api.navi.model.NaviInfo;
import com.amap.api.navi.model.NaviLatLng;
import com.amap.api.navi.view.RouteOverLay;
import com.huika.renrench.R;
import com.huika.renrench.config.UrlConstants;
import com.huika.renrench.control.common.base.BaseAct;
import com.huika.renrench.model.ProjectDetail;
import com.huika.renrench.support.bean.LocationBean;
import com.huika.renrench.support.bean.LocationBean.MyLocationListener;
import com.huika.renrench.support.bean.ShopTransferListBean;
import com.huika.renrench.utils.GaodeMapHelper;

/**
 * 高德地图路径规划
 * 
 * @author fanxing 创建于 Mar 30, 2015
 */
public class GaodeMapRouteActivity extends BaseAct implements
		OnMarkerClickListener, InfoWindowAdapter, OnInfoWindowClickListener,
		LocationSource, MyLocationListener, AMapNaviListener {
	// 目标位置
	public static final String GOAL_LOCATION = "goal_location";

	private LocationBean goalLocationBean;

	private MapView mapView;
	private AMap aMap;
	private LatLng latlng = UrlConstants.HUIKA_LOCATION;

	private OnLocationChangedListener mListener;

	private GaodeMapHelper gaodeMapHelper;

	/** 名称 */
	private TextView tv_name;
	/** 名称 */
	private TextView tv_address;
	private ProjectDetail projectDetail;
	private ShopTransferListBean project;
	private String name;
	private Double latitude=0.0;
	private Double longtitude=0.0;

	/** 路线规划相关 */
	private AMapNavi mAMapNavi;
	// 是否驾车和是否计算成功的标志
	private boolean mIsCalculateRouteSuccess = false;
	// 起点终点坐标
	private NaviLatLng mNaviStart = null;
	private NaviLatLng mNaviEnd = null;
	// 规划线路
	private RouteOverLay mRouteOverLay;
	
//	private AMapNaviViewOptions options;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_gaode_road);
		mAMapNavi = AMapNavi.getInstance(this);
		mAMapNavi.setAMapNaviListener(this);
//		options=new AMapNaviViewOptions();
		
		// new TitleBarHelper(this, R.string.map);

		findViewById(R.id.left_layout).setOnClickListener(this);
		findViewById(R.id.tv_des_go).setOnClickListener(this);
		tv_name = (TextView) findViewById(R.id.tv_name);
		tv_address = (TextView) findViewById(R.id.tv_address);

		projectDetail = (ProjectDetail) getIntent().getSerializableExtra(
				"projectDetail");
		project = (ShopTransferListBean) getIntent().getSerializableExtra(
				"project");
		if (null != projectDetail) {
			name=projectDetail.shopName;
			latitude=projectDetail.latitude;
			longtitude=projectDetail.longitude;
			
			setText(name,projectDetail.address);
			
			tv_name.setText(projectDetail.shopName);
			tv_address.setText(projectDetail.address);
			
		}
		if (null != project) {
			name=project.shopName;
			latitude=project.latitude;
			longtitude=project.longitude;
			setText(name,project.address);
		}
			
			

		/*** 地图相关 **/
		goalLocationBean = new LocationBean();
		goalLocationBean.latitude = latitude;
		goalLocationBean.longtitude = longtitude;
//		goalLocationBean.latitude = projectDetail.latitude;
//		goalLocationBean.longtitude = projectDetail.longitude;
		if (goalLocationBean != null) {
			latlng = new LatLng(goalLocationBean.latitude,
					goalLocationBean.longtitude);
		}
		mapView = (MapView) findViewById(R.id.map);
		mapView.onCreate(savedInstanceState);// 必须要写
		
		mNaviEnd=new NaviLatLng(goalLocationBean.latitude,
				goalLocationBean.longtitude);

		init();

		mRouteOverLay = new RouteOverLay(aMap, null);
	}

	/**
	 * 初始化AMap对象
	 */
	private void init() {
		if (aMap == null) {
			aMap = mapView.getMap();

			aMap.setLocationSource(this);// 设置定位监听
			aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
			aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
			// 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
			aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_FOLLOW);
			aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式
//			options.setEndPointBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.endlopcation_img));
			aMap.setOnMarkerClickListener(this);
			aMap.setOnInfoWindowClickListener(this);

			MarkerOptions markerOptions = new MarkerOptions();
			if (goalLocationBean == null) {
				markerOptions
						.title("惠卡公司")
						.position(latlng)
						.draggable(false)
						.perspective(true)
						.period(10)
						.icon(BitmapDescriptorFactory
								.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
						.snippet("深圳惠卡公司");
			} else {
				markerOptions
						.title("商家地址")
						.position(latlng)
						.draggable(false)
						.perspective(true)
						.period(10)
						.icon(BitmapDescriptorFactory
								.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.endlopcation_img)))
						.snippet(name);
			}
			Marker marker = aMap.addMarker(markerOptions);
			marker.showInfoWindow();// 设置默认显示一个infowinfow

			changeCamera(
					CameraUpdateFactory.newCameraPosition(new CameraPosition(
							latlng, 12, 0, 30)), null);
		}
	}

	private void changeCamera(CameraUpdate update, CancelableCallback callback) {
		aMap.animateCamera(update, 1000, callback);
	}
	
	private void setText(String name,String address){
		if (name.length() > 10) {
			tv_name.setText(name.substring(0, 9)+"...");
		} else {
			tv_name.setText(name);
		}
		tv_address.setText(address);
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onResume() {
		super.onResume();
		mapView.onResume();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onPause() {
		super.onPause();
		mapView.onPause();
		deactivate();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mapView.onSaveInstanceState(outState);
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		mapView.onDestroy();
		if (gaodeMapHelper == null) {
			gaodeMapHelper.stop();
		}

		// 删除监听
		AMapNavi.getInstance(this).removeAMapNaviListener(this);
	}

	/** 地图回调相关 *****************************************/
	/**
	 * 激活定位
	 */
	@Override
	public void activate(OnLocationChangedListener listener) {
		mListener = listener;
		if (gaodeMapHelper == null) {
			gaodeMapHelper = new GaodeMapHelper(this);
			gaodeMapHelper.setmLocationListener(this);
		}
		gaodeMapHelper.setMapLocationListener(mListener);
		gaodeMapHelper.start();
		showToastMsg("定位中...");
	}

	/**
	 * 停止定位
	 */
	@Override
	public void deactivate() {
		mListener = null;
		gaodeMapHelper.stop();
	}

	@Override
	public boolean onMarkerClick(Marker marker) {
		return false;
	}

	@Override
	public View getInfoContents(Marker marker) {
		if (marker.getTitle().equals("商家地址")
				|| marker.getTitle().equals("惠卡公司")) {
			View infoContentView = getLayoutInflater().inflate(
					R.layout.map_item, null);
			((TextView) infoContentView.findViewById(R.id.map_tv_name))
					.setText(marker.getSnippet());
			if (marker.getTitle().equals("惠卡公司")) {

				((TextView) infoContentView
						.findViewById(R.id.map_tv_shop_address))
						.setText(R.string.about_address);
			} else {
				((TextView) infoContentView
						.findViewById(R.id.map_tv_shop_address))
						.setText(R.string.common_null);
			}
			return infoContentView;
		} else {
			return null;
		}
	}

	@Override
	public View getInfoWindow(Marker arg0) {
		
		View infoContentView = getLayoutInflater().inflate(
				R.layout.map_window, null);
		return null;
	}

	@Override
	public void onInfoWindowClick(Marker marker) {
		if (marker.isInfoWindowShown()) {
			marker.hideInfoWindow();
		} else {
			marker.showInfoWindow();
		}
	}

	/**
	 * 定位结果
	 * 
	 * @param locationBean
	 * @author FAN 创建于Mar 18, 2015
	 */
	@Override
	public void onLocation(LocationBean locationBean) {
		gaodeMapHelper.stop();
		if (null==locationBean||TextUtils.isEmpty(locationBean.province)) {
			showToastMsg("定位失败");
		}else{
//			showToastMsg("定位成功");
			mNaviStart = new NaviLatLng(locationBean.latitude, locationBean.longtitude);
		}
	}

	@Override
	public void setRootView() {
		// TODO Auto-generated method stub

	}

	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		super.widgetClick(v);
		switch (v.getId()) {
		case R.id.left_layout:
			finish();
			break;
		case R.id.tv_des_go:
//			showToastMsg("路线规划");
			mIsCalculateRouteSuccess = false;
			calculateFootRoute();
			break;

		default:
			break;
		}
	}

	// 计算步行路线
	private void calculateFootRoute() {
		boolean isSuccess = mAMapNavi.calculateWalkRoute(mNaviStart, mNaviEnd);
		if (!isSuccess) {
			showToastMsg("路线计算失败,检查参数情况");
		}
	}

	@Override
	public void onArriveDestination() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onArrivedWayPoint(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onCalculateRouteFailure(int arg0) {
		// TODO Auto-generated method stub
		if (mIsCalculateRouteSuccess) {
			arg0=RoutePlanErrCode.ERROR_CONNECTION;
			showToastMsg("网络超时或网络失败");
		}
		showToastMsg("路径规划出错" + arg0);
		mIsCalculateRouteSuccess = false;
	}

	@Override
	public void onCalculateRouteSuccess() {
		// TODO Auto-generated method stub
		AMapNaviPath naviPath = mAMapNavi.getNaviPath();
		if (naviPath == null) {
			return;
		}
		// 获取路径规划线路，显示到地图上
		mRouteOverLay.setRouteInfo(naviPath);
		mRouteOverLay.addToMap();
		mIsCalculateRouteSuccess = true;
	}

	@Override
	public void onEndEmulatorNavi() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onGetNavigationText(int arg0, String arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onGpsOpenStatus(boolean arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onInitNaviFailure() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onInitNaviSuccess() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onLocationChange(AMapNaviLocation arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onNaviInfoUpdate(NaviInfo arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onNaviInfoUpdated(AMapNaviInfo arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onReCalculateRouteForTrafficJam() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onReCalculateRouteForYaw() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStartNavi(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTrafficStatusUpdate() {
		// TODO Auto-generated method stub

	}

}
